<template>
  <div class="app-container">

    <el-card class="box-card">
      <h4>{{ $t("Basic_Information") }}</h4>
      <el-form
        ref="goodsForm"
        :rules="rules"
        :model="goods"
        label-width="150px"
      >
<!--        <el-form-item
          :label="$t('选择区域')"
          prop="regionId"
          v-if="!shop && !goods.shopId"
        >-->
        <el-form-item
            :label="$t('选择区域')"
            prop="regionId"
        >
          <el-button type="primary" size="mini" :disabled = "shop && goods.shopId" @click="addRegion">{{
            $t("添加区域")
          }}</el-button>
          <p v-for="(item, i) in regions">
            <el-select
              v-model="regions[i].countryId"
              filterable
              :disabled = "shop && goods.shopId"
              @change="(value) => changeCountry(i, value)"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="country in regionList[i].countrys"
                :label="country.nameCn || country.nameEn"
                :value="country.id"
              >
              </el-option>
            </el-select>

            <el-select
                :disabled = "shop && goods.shopId"
              v-model="regions[i].provinceId"
              filterable
              @change="(value) => changeProvince(i, value)"
              :placeholder="$t('请选择')"
            >
              <el-option

                v-for="province in regionList[i].provinces"
                :label="province.nameCn || province.nameEn"
                :value="province.id"
              >
              </el-option>
            </el-select>

            <el-select
                :disabled = "shop && goods.shopId"
              v-model="regions[i].cityId"
              filterable
              @change="(value) => changeCity(i, regions[i], value)"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="city in regionList[i].citys"
                :label="city.nameCn || city.nameEn"
                :value="city.id"
              >
              </el-option>
            </el-select>

            <el-button type="danger" size="mini" @click="deleteRegion(i)">{{
              $t("Delete")
            }}</el-button>

            <el-row>
              <el-col :span="2">{{ $t("税率类型") }}：</el-col>
              <el-col :span="22">
                <el-checkbox-group v-model="regions[i].taxTypes">
                  <el-checkbox
                    v-for="tax in regionList[i].taxTypes"
                    :label="tax.id"
                    :key="tax.id"
                    >{{ tax.code }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-col>
            </el-row>
          </p>
        </el-form-item>

        <el-form-item :label="$t('Category')">
          <el-cascader :style="{width: '100%'}"
            :options="categoryList"
            v-model="categoryIds"
            :placeholder="$t('请选择')"
            @change="test"
          />
        </el-form-item>
        <el-form-item :label="$t('Merchandise_code')" prop="goodsSn">
          <el-input v-model="goods.goodsSn" />
        </el-form-item>
        <el-form-item :label="$t('Merchandise_name')" prop="name">
          <el-input v-model="goods.name" />
        </el-form-item>
<!--        <el-form-item :label="$t('缩写')" prop="subhead">
          <el-input v-model="goods.subhead" />
        </el-form-item>
        <el-form-item :label="$t('计量单位')" prop="unit">
          <el-input v-model="goods.unit" />
        </el-form-item>-->
        <el-form-item :label="$t('About_the_merchandise')">
          <el-input v-model="goods.brief" />
        </el-form-item>
        <el-form-item :label="$t('Goods_picture')">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :on-success="uploadPicUrl"
            :on-remove="handleGoodsPicRemove"
            :show-file-list="false"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-if="goods.picUrl" :src="goods.picUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <label
              v-if="goods.picUrl"
              class="el-upload-list__item-status-label avatar-uploader__status_label"
              @click.stop="handleGoodsPicRemove()"
              ><i class="el-icon-delete"></i
            ></label>
          </el-upload>
        </el-form-item>

        <el-form-item :label="$t('Gallery')">
          <el-upload
              :class="{hide:hideUpload}"

              :action="uploadPath"
            :headers="headers"
            :limit="10"
            :file-list="galleryFileList"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-remove="handleRemove"
            multiple
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <span :style="{color:'#ec8751'}"><i class="el-icon-upload"></i>{{ this.$t('上传文件个数不能超出限制！最多上传10张图片!') }}</span>
        </el-form-item>
        <el-form-item :label="$t('Goods_details')">
          <el-input type="textarea" :init="editorInit" v-model="goods.detail" />
        </el-form-item>
<!--        <el-form-item :label="$t('操作说明')">
          <el-input type="textarea" v-model="goods.operationDesc"></el-input>
        </el-form-item>-->
        <el-form-item :label="$t('Goods_tax_type')" v-if="shop">
          <el-checkbox-group v-model="regions[0].taxTypes">
            <el-checkbox
              v-for="tax in shopTaxTypes"
              :label="tax.id"
              :key="tax.id"
              >{{ tax.code }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </el-card>
    <!--商品规格-->
    <el-card class="box-card">
      <h4 ref="goodsSpecificationsTitle">{{ $t("Goods_specifications") }}</h4>
      <!--      <el-button :plain1="true" type="primary" icon="el-icon-circle-plus" @click="handleSpecificationShow">{{ $t('添加商品原料') }}</el-button>-->
      <el-button
        :plain1="true"
        type="warning"
        icon="el-icon-circle-plus"
        @click="handleFormulaShow"
      >{{ $t("选择配方") }}</el-button
      >
      <el-tag v-show="goodsFormulaName">{{ $t("当前配方") }}：{{ goodsFormulaName }}</el-tag>
      <el-button
        :style="{float:'right'}"
        v-show="goodsFormulaName"
        :plain1="true"
        icon="el-icon-circle-close"
        @click="handleFormulaUnbundle"
      >{{ $t("解除配方") }}</el-button
      >
      <!-- 配方列表 -->
      <el-dialog :visible.sync="formulaVisiable" :title="$t('选择配方')" >
        <el-form :inline="true" :model="formulaQueryParam" class="demo-form-inline">
          <el-form-item :label="$t('配方名称')">
            <el-input
              v-model="formulaQueryParam.formulaName"
              clearable
              class="filter-item"
              style="width: 200px"
              @clear="handleSearchFormulaList"
              :placeholder="$t('配方名称')"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              class="filter-item"
              icon="el-icon-search"
              @click="handleSearchFormulaList"
            >{{ $t("Search") }}</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          v-loading="formulaListLoading"
          :data="formulaList"
          @current-change="handleCurrentChange"
          highlight-current-row
          :element-loading-text="$t('Searching')"
          max-height="400"
        >
          <el-table-column
            type="index"
            :index="getIndex"
            :label="$t('序号')"
          ></el-table-column>

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('配方名称')"
            prop="formulaName"
          />

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('配方类型')"
            prop="formulaTypeId"
          >
            <template slot-scope="scope">
              <span :style="{ color: formateFormulaTypeColour(scope.row) }">{{
                  formateFormulaType(scope.row)
                }}</span>
            </template></el-table-column
          >

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('配方备注')"
            prop="formulaRemark"
          />
          <el-table-column align="center" :label="$t('Operate')" width="200" class-name="small-padding fixed-width">
            <template slot="header" slot-scope="{row}">
              {{$t('Operate')}}
              <i class="el-icon-s-tools" style="color: #d35e32"></i>
            </template>
            <template slot-scope="scope">
                <el-button type="text" @click="handlePath(scope.row)">{{$t('查看配方')}}</el-button>
            </template>
          </el-table-column>
          <!-- Vue 2 的空状态提示（使用 slot="empty"） -->
          <div slot="empty" style="padding: 16px 0;">
            <el-link @click="handleCreatePath">
              {{ $t('没有找到配方？点击去创建') }}
            </el-link>
          </div>
        </el-table>
        <pagination :total="formulaQueryParam.total" :page.sync="formulaQueryParam.page" :limit.sync="formulaQueryParam.limit" @pagination="getFormulaList()" />
        <!-- 按钮容器 -->
        <div class="dialog-footer">
          <el-button type="primary" @click="sumbitGoodsFormula">
            {{ $t("确定") }}
          </el-button>
        </div>
      </el-dialog>

      <!-- 商品规格列表 -->
      <el-table v-show="showGoodsFormulaTable === true" :data="specifications">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table :data="scope.row.merchandises">
              <el-table-column property="merchandiseSn" :label="$t('Merchandise_number')" />
              <el-table-column property="merchandiseName" :label="$t('品名')" />
              <el-table-column property="model" :label="$t('规格')" />
              <el-table-column property="number" :label="$t('数量')" />
              <el-table-column property="basicUnit" :label="$t('单位')" />
              <el-table-column align="center" :label="$t('Operate')" width="280" class-name="small-padding fixed-width">
                <template slot="header" slot-scope="{row}">
                  {{$t('Operate')}}
                  <i class="el-icon-s-tools" style="color: #d35e32"></i>
                </template>
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" plain1 round size="mini" @click="handleEditSpecMer(scope.row)">
                  </el-button>
                  <el-button type="danger" icon="el-icon-delete" plain1 round size="mini" @click="handleDeleteSpecMer(scope.row)">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column property="specification" :label="$t('Specification_name')" />
        <el-table-column property="value" :label="$t('Specification_value')">
          <template slot-scope="scope">
            <el-tag type="primary">
              {{ scope.row.value }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="price" :label="$t('Price')">
          <template slot-scope="scope">
            {{ scope.row.price | floorTwoDecimal }}
          </template>
        </el-table-column>
        <el-table-column property="picUrl" :label="$t('Specification_images')">
          <template slot-scope="scope">
            <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40">
          </template>
        </el-table-column>
        <el-table-column property="sort" :label="$t('序号')" />
        <el-table-column align="center" :label="$t('Operate')" width="300" class-name="small-padding fixed-width">
          <template slot="header" slot-scope="{row}">
            {{$t('Operate')}}
            <i class="el-icon-s-tools" style="color: #d35e32"></i>
          </template>
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" plain1 round size="mini" @click="handleSpecificationEdit(scope.row)">{{ $t('Edit') }}
            </el-button>
            <el-button type="danger"  icon="el-icon-delete" plain1 round size="mini" @click="handleSpecificationDelete(scope.row)">{{ $t('Delete') }}
            </el-button>
            <el-button type="primary" icon="el-icon-circle-plus" plain1 round size="mini" style="width: 120px" @click="handleAddSpecMer(scope.row)">
              {{ $t('添加原料') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--添加规格-->
      <el-dialog :visible.sync="specVisiable" :title="$t('Specification_settings')">
        <el-form ref="specForm" :rules="specRules" :model="specForm" status-icon label-position="left"
                 label-width="200px" style="width: 500px; margin-left:50px;">
          <el-form-item :label="$t('Specification_name')" prop="specification">
            <el-input v-model="specForm.specification" />
          </el-form-item>
          <el-form-item :label="$t('Specification_value')" prop="value">
            <el-input v-model="specForm.value" />
          </el-form-item>
          <el-form-item :label="$t('Price')" prop="price">
            <el-input-number v-model="specForm.price" :min="0" :controls="false" :precision="2"></el-input-number>
          </el-form-item>
          <el-form-item :label="$t('Specification_images')" prop="picUrl">
            <el-upload :headers="headers" :action="uploadPath" :on-success="uploadSpecPicUrl"
                       :on-remove="handleSpecRemove" :show-file-list="false" class="avatar-uploader"
                       accept=".jpg,.jpeg,.png,.gif">
              <img v-if="specForm.picUrl" :src="specForm.picUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
              <label v-if="specForm.picUrl" class="el-upload-list__item-status-label avatar-uploader__status_label"
                     @click.stop="handleSpecRemove()"><i class="el-icon-delete"></i></label>
            </el-upload>
          </el-form-item>
          <el-form-item :label="$t('序号')" prop="sort">
            <el-input-number v-model="specForm.sort" :min="0" :controls="false" :precision="0"></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button icon="el-icon-error" plain1 round @click="specVisiable = false">{{ $t('Cancel') }}</el-button>
          <el-button icon="el-icon-success" plain1 round type="primary" @click="handleSpecificationAdd">{{ $t('Confirm') }}</el-button>
        </div>
      </el-dialog>
      <!--编辑规格-->
      <el-dialog :visible.sync="specEditVisiable" :title="$t('Specification_settings')">
        <el-form ref="specEditForm" :rules="specRules" :model="specEditForm" status-icon label-position="left"
                 label-width="200px" style="width: 500px; margin-left:50px;">
          <el-form-item :label="$t('Specification_name')" prop="specification">
            <el-input v-model="specEditForm.specification" />
          </el-form-item>
          <el-form-item :label="$t('Specification_value')" prop="value">
            <el-input v-model="specEditForm.value" />
          </el-form-item>
          <el-form-item :label="$t('Price')" prop="price">
            <el-input-number v-model="specEditForm.price" :min="0" :controls="false" :precision="2"></el-input-number>
          </el-form-item>
          <el-form-item :label="$t('Specification_images')" prop="picUrl">
            <el-upload :headers="headers" :action="uploadPath" :on-success="uploadSpecEditPicUrl"
                       :on-remove="handleSpecEditRemove" :show-file-list="false" class="avatar-uploader"
                       accept=".jpg,.jpeg,.png,.gif">
              <img v-if="specEditForm.picUrl" :src="specEditForm.picUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
              <label v-if="specEditForm.picUrl" class="el-upload-list__item-status-label avatar-uploader__status_label"
                     @click.stop="handleSpecEditRemove()"><i class="el-icon-delete"></i></label>
            </el-upload>
          </el-form-item>
          <el-form-item :label="$t('序号')" prop="sort">
            <el-input-number v-model="specEditForm.sort" :min="0" :controls="false" :precision="0"></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button icon="el-icon-error" plain1 round @click="specEditVisiable = false">{{ $t('Cancel') }}</el-button>
          <el-button icon="el-icon-success" plain1 round type="primary" @click="handleSpecificationEditSubmit">{{ $t('Confirm') }}</el-button>
        </div>
      </el-dialog>
      <!--原料设置-->
      <el-dialog :visible.sync="specMerVisiable" :title="$t('配置原料')">
        <el-form ref="specMerForm" :rules="specMerRules" :model="specMerForm" status-icon label-position="left"
                 label-width="200px" style="width: 500px; margin-left:50px;">
          <el-form-item :label="$t('选择原料')" prop="merchandiseId">
            <el-select v-model="specMerForm.merchandiseId" filterable :placeholder="$t('请选择')"
                       @change="changeSpecMerFormMerchandise">
              <el-option v-for="item in specMerList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('规格')" prop="model">
            <el-input-number v-model="specMerForm.model" :min="0" :controls="false" :precision="2">
            </el-input-number>
          </el-form-item>
          <el-form-item :label="$t('数量')" prop="number">
            <el-input-number v-model="specMerForm.number" :min="0" :controls="false" :precision="0"></el-input-number>
          </el-form-item>
          <el-form-item :label="$t('消耗系数')" prop="consumeRatio">
            <el-input-number v-model="specMerForm.consumeRatio" :min="0" :controls="false" :precision="2">
            </el-input-number>
          </el-form-item>
          <el-form-item :label="$t('单位')">
            {{ specMerForm.basicUnit }}
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button icon="el-icon-error" plain1 round @click="specMerVisiable = false">{{ $t('Cancel') }}</el-button>
          <el-button icon="el-icon-success" plain1 round type="primary" @click="handleSpecMerSubmit">{{ $t('Confirm') }}</el-button>
        </div>
      </el-dialog>


      <!-- 配方规格列表 -->
      <el-table
        v-show="showGoodsFormulaTable === false"
        v-loading="goodsFormulaSpecificationsLoading"
        :data="goodsFormulaSpecificationsList"
        :element-loading-text="$t('Searching')"
      >
        <el-table-column
          type="index"
          :index="getIndex"
          width="200"
          :label="$t('序号')"
        >
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          :label="$t('规格名称')"
          prop="specificationsName"
        />

        <el-table-column
          align="center"
          min-width="100"
          :label="$t('规格值')"
          prop="specificationsValue"
        />

        <!-- <el-table-column
          align="center"
          min-width="100"
          :label="$t('规格图片')"
          prop="specificationsImg"
        /> -->

        <el-table-column
          align="center"
          min-width="100"
          :label="$t('规格图片')"
          prop="specificationsImg"
        >
          <template slot-scope="scope">
            <el-image
              preview-src-list
              style="border-radius: 7%; width: 80px"
              :src="scope.row.specificationsImg"
              width="20"
            >
              <div slot="error" class="image-slot">
                <i
                  style="font-size: 30px"
                  class="el-icon-picture-outline"
                ></i>
              </div>
            </el-image>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          :label="$t('规格价格')"
          prop="specificationsPrice">
          <template slot-scope="scope">
            ${{scope.row.specificationsPrice}}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          :label="$t('是否默认')"
          prop="isDefault"
        >
          <template slot-scope="scope">
            <span>{{
                scope.row.isDefault ? "是" : "否"
              }}</span>
          </template></el-table-column>

        <el-table-column
          align="center"
          :label="$t('Operate')"
          width="200"
          class-name="small-padding fixed-width"
        >
          <template slot="header" slot-scope="{ row }">
            {{ $t("Operate") }}
            <i class="el-icon-setting" style="color: #d35e32"></i>
          </template>

          <template slot-scope="scope">
            <el-button
              type="primary"
              round
              icon="el-icon-edit"
              plain1
              size="mini"
              @click="
                handleFormulaSpecificationsDataProportioningShow(scope.row)
              "
            >{{ $t("详情") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 配方规格数据配比详情 -->
      <el-dialog
        :visible.sync="formulaSpecificationsDataProportioningVisiable"
        :title="$t('规格详情')"
      >
        <!-- 查询结果 -->
        <el-table
          v-loading="formulaSpecificationsDataProportioningLoading"
          :data="formulaSpecificationsDataProportioningList"
          :element-loading-text="$t('Searching')"
          border
          stripe
          fit
          highlight-current-row
          row-key="id"
        >
          <el-table-column
            align="center"
            min-width="100"
            :label="$t('原料名称')"
            prop="lumiereFormulaMaterial.materialName"
          />

          <!-- <el-table-column
            align="center"
            min-width="100"
            :label="$t('原料图片')"
            prop="lumiereFormulaMaterial.materialImg"
          >
            <template slot-scope="scope">
              <el-image
                preview-src-list
                style="border-radius: 7%; width: 80px"
                :src="scope.row.lumiereFormulaMaterial.materialImg"
                width="20"
              >
                <div slot="error" class="image-slot">
                  <i
                    style="font-size: 30px"
                    class="el-icon-picture-outline"
                  ></i>
                </div>
              </el-image>
            </template>
          </el-table-column> -->

          <!-- <el-table-column
            align="center"
            min-width="100"
            :label="$t('配方图片')"
            prop="lumiereFormulaMaterial.materialImg"
          /> -->

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('额外收费')"
            prop="surcharge"
          />

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('规格剂量')"
            prop="specificationsDose"
          />

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('数量')"
            prop="quantity"
          />

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('计费条件')"
            prop="chargingCondition"
          />

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('数量上限')"
            prop="quantityRestrict"
          />

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('单位')"
            prop="unit"
          />

          <el-table-column
            align="center"
            min-width="100"
            :label="$t('计费条件')"
            prop="chargingMode"
          />
        </el-table>
        <!-- 按钮容器 -->
        <div class="dialog-footer">
          <!--          <el-button type="primary" @click="handeleAddSpecifications">
                      {{ $t("去编辑") }}
                    </el-button>-->
        </div>
      </el-dialog>

    </el-card>
    <!-- 第二个弹框-编辑规格 -->
    <dic class="dialogCenter">
      <el-dialog
        :title="$t('查看规格')"
        :visible.sync="dialogVisible2"
        width="40%"
        :before-close="handleCloseFormulaSpecifications"
      >
        <!-- 表单内容 -->
        <div>
          <el-form
            :model="formulaSpecificationsForm"
            :rules="rules"
            ref="formulaSpecificationsForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item :label="$t('规格名称')">
              <el-input
                disabled
                v-model="formulaSpecificationsForm.specificationsName"
                :placeholder="$t('请输入规格名称')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('规格值')">
              <el-input
                disabled
                v-model="formulaSpecificationsForm.specificationsValue"
                :placeholder="$t('请输入规格值')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('规格图片')" prop="specificationsImg">
              <el-upload
                disabled
                :headers="headers"
                :action="uploadPath"
                :show-file-list="false"
                :on-success="uploadPicUrl"
                class="avatar-uploader"
                accept=".jpg,.jpeg,.png,.gif"
              >
                <img
                  v-if="formulaSpecificationsForm.specificationsImg"
                  :src="formulaSpecificationsForm.specificationsImg"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <label
                  v-if="formulaSpecificationsForm.specificationsImg"
                  class="el-upload-list__item-status-label avatar-uploader__status_label"
                  @click.stop="handleRemove()"
                  ><i class="el-icon-delete"></i
                ></label>
              </el-upload>
            </el-form-item>

            <el-form-item :label="$t('规格价格')">
              <el-input
                disabled
                v-model="formulaSpecificationsForm.specificationsPrice"
                :placeholder="$t('请输入规格价格')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('是否默认')">
              <el-switch
                disabled
                v-model="formulaSpecificationsForm.isDefault"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-text="$t('是')"
                :inactive-text="$t('否')"
              >
              </el-switch>
            </el-form-item>

            <!-- <el-form-item>
              <el-button
                icon="el-icon-check"
                type="primary"
                @click="
                  handerUpdateFormulaSpecifications('formulaSpecificationsForm')
                "
                >{{ $t("提交编辑") }}</el-button
              >
            </el-form-item> -->
          </el-form>
        </div>
      </el-dialog>
    </dic>

    <!-- 第四个弹框-添加可替换原料 -->
    <dic class="dialogCenter">
      <el-dialog
        :title="$t('可替换原料')"
        :visible.sync="dialogVisible4"
        width="40%"
        :before-close="handleCloseFormulaSpecifications"
      >
        <!-- 表单内容 -->
        <div>
          <el-form
            :model="replaceableMaterialForm"
            :rules="rules"
            ref="replaceableMaterialForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <!-- <el-form-item :label="$t('原料名称')">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.materialName"
                :placeholder="$t('请输入原料名称')"
              ></el-input>
            </el-form-item> -->

              <el-form-item
                      :label="$t('原料分类')"
                      prop="materialClassificationId"
              >
                  <el-cascader
                          v-model="replaceableMaterialForm.lumiereReplaceableMaterial.materialClassificationId"
                          :options="materialList"
                          :props="{
                  label: 'classificationName',
                  value: 'id',
                }"
                          :show-all-levels="false"
                          clearable
                          @change="handleCascaderChangeMaterialId"
                  ></el-cascader>
              </el-form-item>

            <el-form-item :label="$t('原料名称')" prop="lumiereReplaceableMaterial.materialName">
              <el-select
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.materialName"
                filterable
                @change="handleAccessoryMerChangeNew"
                :placeholder="$t('请选择原料名称')"
              >
                <el-option
                  v-for="item in merchandise"
                  :value="item.name"
                  :label="item.name"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span
                    v-if="item.isRrc"
                    style="float: right; color: #8492a6; font-size: 13px"
                    ><i class="el-icon-coffee"></i>{{ $t("原料") }}</span
                  >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('原料图片')" prop="lumiereReplaceableMaterial.materialImg">
              <el-upload
                :headers="headers"
                :action="uploadPath"
                :show-file-list="false"
                :on-success="uploadPicUrl"
                class="avatar-uploader"
                accept=".jpg,.jpeg,.png,.gif"
              >
                <img
                  v-if="replaceableMaterialForm.lumiereReplaceableMaterial.materialImg"
                  :src="replaceableMaterialForm.lumiereReplaceableMaterial.materialImg"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <label
                  v-if="replaceableMaterialForm.lumiereReplaceableMaterial.materialImg"
                  class="el-upload-list__item-status-label avatar-uploader__status_label"
                  @click.stop="handleRemove()"
                  ><i class="el-icon-delete"></i
                ></label>
              </el-upload>
            </el-form-item>

            <el-form-item :label="$t('规格剂量')" prop="lumiereReplaceableMaterial.specificationsDose">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.specificationsDose"
                :placeholder="$t('请输入规格剂量')"
              ></el-input>
            </el-form-item>

             <el-form-item :label="$t('数量')" prop="lumiereReplaceableMaterial.quantity">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.quantity"
                :placeholder="$t('请输入数量')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('计费条件')" prop="lumiereReplaceableMaterial.chargingCondition">
              <div style="display: flex; gap: 10px">
<!--                <el-select
                  v-model="replaceableMaterialForm.lumiereReplaceableMaterial.chargingCondition"
                  filterable
                  @clear="handleFilter"
                  :placeholder="$t('请选择')"
                  clearable
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>-->
                <el-input
                  style="flex: 1"
                  v-model="replaceableMaterialForm.lumiereReplaceableMaterial.chargingConditionNumber"
                  :placeholder="$t('请输入计费金额')"
                >
                  <template slot="prepend">{{$t('大于')}}</template>
                </el-input>
              </div>
            </el-form-item>

            <el-form-item :label="$t('额外收费')" prop="lumiereReplaceableMaterial.surcharge">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.surcharge"
                :placeholder="$t('请输入额外收费')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('数量上限')" prop="lumiereReplaceableMaterial.quantityRestrict">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.quantityRestrict"
                :placeholder="$t('请输入数量上限')"
              ></el-input>
            </el-form-item>

            <!-- <el-form-item :label="$t('单位')" prop="lumiereReplaceableMaterial.unit">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.unit"
                :placeholder="$t('请输入单位')"
              ></el-input>
            </el-form-item> -->

            <el-form-item :label="$t('单位')">
              {{accessoryForm.basicUnit}}
            </el-form-item>

            <el-form-item :label="$t('消耗系数')" prop="lumiereReplaceableMaterial.consumeSystem">
              <el-select v-model="replaceableMaterialForm.lumiereReplaceableMaterial.consumeSystem" placeholder="请输入消耗系数">
                <el-option
                  v-for="item in consumeSystemOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('计费方式')" prop="lumiereReplaceableMaterial.chargingMode">
              <el-select
                filterable
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.chargingMode"
                @clear="handleFilter"
                :placeholder="$t('状态')"
                clearable
              >
                <el-option :label="$t('按份计费')" value="按份计费"></el-option>
                <el-option :label="$t('按次计费')" value="按次计费"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                icon="el-icon-check"
                type="primary"
                @click="submitAddReplaceableMaterial(replaceableMaterialForm)"
                >{{ $t("添加可替换原料") }}</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </dic>

    <!-- 第五个弹框-编辑可替换原料 -->
    <dic class="dialogCenter">
      <el-dialog
        :title="$t('编辑可替换原料')"
        :visible.sync="dialogVisible5"
        width="40%"
        :before-close="handleCloseFormulaSpecifications"
      >
        <!-- 表单内容 -->
        <div>
          <el-form
            :model="replaceableMaterialForm"
            :rules="rules"
            ref="replaceableMaterialForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <!-- <el-form-item :label="$t('原料名称')" prop="lumiereReplaceableMaterial.materialName">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.materialName"
                :placeholder="$t('请输入原料名称')"
              ></el-input>
            </el-form-item> -->

            <el-form-item :label="$t('原料名称')" prop="lumiereReplaceableMaterial.materialName">
              <el-select
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.materialName"
                filterable
                @change="handleAccessoryMerChangeNew"
                :placeholder="$t('请选择原料名称')"
              >
                <el-option
                  v-for="item in merchandise"
                  :value="item.name"
                  :label="item.name"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span
                    v-if="item.isRrc"
                    style="float: right; color: #8492a6; font-size: 13px"
                    ><i class="el-icon-coffee"></i>{{ $t("原料") }}</span
                  >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('原料图片')" prop="lumiereReplaceableMaterial.materialImg">
              <el-upload
                :headers="headers"
                :action="uploadPath"
                :show-file-list="false"
                :on-success="uploadPicUrl"
                class="avatar-uploader"
                accept=".jpg,.jpeg,.png,.gif"
              >
                <img
                  v-if="replaceableMaterialForm.lumiereReplaceableMaterial.materialImg"
                  :src="replaceableMaterialForm.lumiereReplaceableMaterial.materialImg"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <label
                  v-if="replaceableMaterialForm.lumiereReplaceableMaterial.materialImg"
                  class="el-upload-list__item-status-label avatar-uploader__status_label"
                  @click.stop="handleRemove()"
                  ><i class="el-icon-delete"></i
                ></label>
              </el-upload>
            </el-form-item>

            <el-form-item :label="$t('规格剂量')" prop="lumiereReplaceableMaterial.specificationsDose">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.specificationsDose"
                :placeholder="$t('请输入规格剂量')"
              ></el-input>
            </el-form-item>

             <el-form-item :label="$t('数量')" prop="lumiereReplaceableMaterial.quantity">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.quantity"
                :placeholder="$t('请输入数量')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('计费条件')" prop="lumiereReplaceableMaterial.chargingCondition">
              <div style="display: flex; gap: 10px">
<!--                <el-select
                  v-model="replaceableMaterialForm.lumiereReplaceableMaterial.chargingCondition"
                  filterable
                  @clear="handleFilter"
                  :placeholder="$t('请选择')"
                  clearable
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>-->
                <el-input
                  style="flex: 1"
                  v-model="replaceableMaterialForm.lumiereReplaceableMaterial.chargingCondition"
                  :placeholder="$t('请输入计费条件')"
                >
                  <template slot="prepend">{{$t('大于')}}</template>
                </el-input>
              </div>
            </el-form-item>

            <el-form-item :label="$t('额外收费')" prop="lumiereReplaceableMaterial.surcharge">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.surcharge"
                :placeholder="$t('请输入额外收费')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="$t('数量上限')" prop="lumiereReplaceableMaterial.quantityRestrict">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.quantityRestrict"
                :placeholder="$t('请输入数量上限')"
              ></el-input>
            </el-form-item>

            <!-- <el-form-item :label="$t('单位')" prop="lumiereReplaceableMaterial.unit">
              <el-input
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.unit"
                :placeholder="$t('请输入单位')"
              ></el-input>
            </el-form-item> -->

            <el-form-item :label="$t('单位')">
              {{accessoryForm.basicUnit}}
            </el-form-item>

            <el-form-item :label="$t('消耗系数')" prop="lumiereReplaceableMaterial.consumeSystem">
              <el-select v-model="replaceableMaterialForm.lumiereReplaceableMaterial.consumeSystem" placeholder="请输入消耗系数">
                <el-option
                  v-for="item in consumeSystemOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('计费方式')" prop="lumiereReplaceableMaterial.chargingMode">
              <el-select
                filterable
                v-model="replaceableMaterialForm.lumiereReplaceableMaterial.chargingMode"
                @clear="handleFilter"
                :placeholder="$t('状态')"
                clearable
              >
                <el-option :label="$t('按份计费')" value="1"></el-option>
                <el-option :label="$t('按次计费')" value="0"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                icon="el-icon-check"
                type="primary"
                @click="submitUpdateReplaceableMaterial(replaceableMaterialForm.lumiereReplaceableMaterial)"
                >{{ $t("编辑可替换原料") }}</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </dic>

    <!-- 属性 -->
    <el-card class="box-card">
      <h4>{{ $t("商品属性") }}
        <el-tooltip  effect="dark" placement="right">
          <div slot="content">属性提示信息：<br/>商品属性是指用于描述商品特征和特性的各种要素，例如商品的温度、糖度。</div>
          <i class="el-icon-question"></i>
        </el-tooltip>
      </h4>

      <el-button
        icon="el-icon-circle-plus"
        :plain1="true"
        type="primary"
        @click="handlePropertyShow"
        >{{ $t("Add") }}</el-button
      >

      <el-table :data="properties">
        <el-table-column property="name" :label="$t('属性名称')" />
        <el-table-column property="values" :label="$t('属性值')">
          <template slot-scope="scope">
            {{ scope.row.values.join(",") }}
          </template>
        </el-table-column>
        <el-table-column property="sort" :label="$t('序号')" />
        <el-table-column
          align="center"
          :label="$t('Operate')"
          width="250"
          class-name="small-padding fixed-width"
        >
          <template slot="header" slot-scope="{ row }">
            {{ $t("Operate") }}
            <i class="el-icon-s-tools" style="color: #d35e32"></i>
          </template>
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              plain1
              round
              type="primary"
              size="mini"
              @click="handlePropertyEdit(scope.row)"
              >{{ $t("Edit") }}</el-button
            >
            <el-button
              icon="el-icon-delete"
              plain1
              round
              type="danger"
              size="mini"
              @click="handlePropertyDelete(scope.row)"
              >{{ $t("Delete") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="propertyVisiable" :title="$t('属性设置')">
        <el-form
          ref="propertyForm"
          :rules="propertyRules"
          :model="propertyForm"
          status-icon
          label-position="left"
          label-width="200px"
          style="width: 500px; margin-left: 50px"
        >
          <el-form-item :label="$t('属性名称')" prop="name">
            <el-input v-model="propertyForm.name" />
          </el-form-item>
          <el-form-item :label="$t('序号')" prop="sort">
            <el-input-number
              v-model="propertyForm.sort"
              :min="0"
              :controls="false"
              :precision="0"
            ></el-input-number>
          </el-form-item>

          <el-form-item :label="$t('属性值')">
            <el-button
              :plain1="true"
              icon="el-icon-circle-plus"
              plain1
              round
              type="primary"
              @click="handlePropertyValueAdd"
              >{{ $t("Add") }}</el-button
            >
          </el-form-item>

          <el-form-item prop="values">
            <p v-for="(val, index) in propertyForm.values" :key="index">
              <el-row>
                <el-col :span="16">
                  <el-input v-model="propertyForm.values[index]" />
                </el-col>
                <el-col :span="4">
                  <el-button
                    icon="el-icon-delete"
                    plain1
                    round
                    type="danger"
                    size="mini"
                    @click="handlePropertyValueDelete(index)"
                  >
                  </el-button>
                </el-col>
                <el-col :span="4">
                  <el-radio :label="val" v-model="propertyForm.isDefault"
                    >是否默认</el-radio
                  >
                </el-col>
              </el-row>
            </p>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            icon="el-icon-error"
            plain1
            round
            @click="propertyVisiable = false"
            >{{ $t("Cancel") }}</el-button
          >
          <el-button
            icon="el-icon-success"
            plain1
            round
            type="primary"
            @click="handlePropertyAdd"
            >{{ $t("Confirm") }}</el-button
          >
        </div>
      </el-dialog>
    </el-card>

    <!-- 辅料 -->
     <el-card v-show="false" class="box-card">
      <h4>{{ $t("商品辅料") }}</h4>
      <el-button
        icon="el-icon-circle-plus"
        :plain1="true"
        type="primary"
        @click="handleAccessoryShow"
        >{{ $t("Add") }}</el-button
      >

      <el-table :data="accessories">
        <el-table-column property="groupName" :label="$t('辅料名')" />
        <el-table-column property="name" :label="$t('Merchandise_name')" />
        <el-table-column property="number" :label="$t('数量')" />
        <el-table-column property="price" :label="$t('价格')">
          <template slot-scope="scope">
            {{ scope.row.price | floorTwoDecimal }}
          </template>
        </el-table-column>
        <el-table-column property="costType" :label="$t('计费方式')">
          <template slot-scope="scope">
            {{ getCostType(scope.row.costType) }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('Operate')"
          width="250"
          class-name="small-padding fixed-width"
        >
          <template slot="header" slot-scope="{ row }">
            {{ $t("Operate") }}
            <i class="el-icon-s-tools" style="color: #d35e32"></i>
          </template>
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              plain1
              round
              type="primary"
              size="mini"
              @click="handleAccessoryEdit(scope.row)"
              >{{ $t("Edit") }}</el-button
            >
            <el-button
              icon="el-icon-delete"
              plain1
              round
              type="danger"
              size="mini"
              @click="handleAccessoryDelete(scope.row)"
              >{{ $t("Delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="accessoryVisiable" :title="$t('辅料设置')">
        <el-form
          ref="accessoryForm"
          :rules="accessoryRules"
          :model="accessoryForm"
          status-icon
          label-position="left"
          label-width="200px"
          style="width: 500px; margin-left: 50px"
        >
          <el-form-item :label="$t('辅料名')" prop="groupName">
            <el-input v-model="accessoryForm.groupName" />
          </el-form-item>

          <el-form-item :label="$t('选择原料')" prop="merchandiseId">
            <el-select
              v-model="accessoryForm.merchandiseId"
              filterable
              @change="handleAccessoryMerChange"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="item in merchandise"
                :value="item.id"
                :label="item.name"
              >
                <span style="float: left">{{ item.name }}</span>
                <span
                  v-if="item.isRrc"
                  style="float: right; color: #8492a6; font-size: 13px"
                  ><i class="el-icon-coffee"></i>{{ $t("原料") }}</span
                >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('辅料组名')" prop="accessoryGroupName">
            <el-select
              clearable
              filterable
              v-model="accessoryForm.accessoryGroupName"
              :placeholder="$t('请选择')"
            >
              <el-option
                key="Syrups"
                :label="$t('Syrups')"
                value="Syrups"
              ></el-option>
              <el-option
                key="Milk"
                :label="$t('Milk')"
                value="Milk"
              ></el-option>
              <el-option
                key="Toppings"
                :label="$t('Toppings')"
                value="Toppings"
              ></el-option>
              <el-option
                key="Cold Foam"
                :label="$t('Cold Foam')"
                value="Cold Foam"
              ></el-option>
              <el-option
                key="Add Shot"
                :label="$t('Add Shot')"
                value="Add Shot"
              ></el-option>
              <el-option
                key="Others"
                :label="$t('Others')"
                value="Others"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            style="margin-top: 40px"
            :label="$t('价格')"
            prop="price"
          >
            <el-input-number
              v-model="accessoryForm.price"
              :min="0"
              :controls="false"
              :precision="2"
            ></el-input-number>
          </el-form-item>
          <el-form-item :label="$t('数量')" prop="number">
            <el-input-number
              v-model="accessoryForm.number"
              :min="0"
              :controls="false"
              :precision="0"
            ></el-input-number>
          </el-form-item>

          <el-form-item :label="$t('多加')" prop="muchContent">
            <el-input-number
              v-model="accessoryForm.muchContent"
              :min="0"
              :controls="false"
              :precision="2"
            >
            </el-input-number>
          </el-form-item>

          <el-form-item :label="$t('少量')" prop="fewContent">
            <el-input-number
              v-model="accessoryForm.fewContent"
              :min="0"
              :controls="false"
              :precision="2"
            >
            </el-input-number>
          </el-form-item>

          <el-form-item :label="$t('剂量')" prop="consumeRatio">
            <el-input-number
              v-model="accessoryForm.dosage"
              :min="0"
              :controls="false"
              :precision="2"
            >
            </el-input-number>
          </el-form-item>
          <el-form-item :label="$t('消耗系数')" prop="consumeRatio">
            <el-input-number
              v-model="accessoryForm.consumeRatio"
              :min="0"
              :controls="false"
              :precision="2"
            >
            </el-input-number>
          </el-form-item>
          <el-form-item :label="$t('单位')">
            {{ accessoryForm.basicUnit }}
          </el-form-item>
          <el-form-item :label="$t('计费方式')" prop="costType">
            <el-select
              v-model="accessoryForm.costType"
              :placeholder="$t('请选择')"
            >
              <el-option
                v-for="item in costTypeData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            icon="el-icon-error"
            plain1
            @click="accessoryVisiable = false"
            >{{ $t("Cancel") }}</el-button
          >
          <el-button
            icon="el-icon-success"
            plain1
            type="primary"
            @click="handleAccessoryAdd"
            >{{ $t("Confirm") }}</el-button
          >
        </div>
      </el-dialog>
    </el-card>

    <el-card class="box-card">
      <h4>{{ $t("Other_information") }}</h4>
      <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
        <!-- <el-form-item :label="$t('Points_earned_after_purchase')" prop="giveAwayPoints">
          <el-input v-model.number="goods.giveAwayPoints"/>
        </el-form-item> -->
        <el-form-item :label="$t('Merchandise_label')">
          <el-checkbox :value="true" v-model="goods.isNew">{{
            $t("New_product")
          }}</el-checkbox>
          <el-checkbox :value="true" v-model="goods.isHot">{{
            $t("Recommendation")
          }}</el-checkbox>
        </el-form-item>
        <el-form-item :label="$t('Services')" prop="isReturn">
          <el-radio-group v-model="goods.isReturn">
            <el-radio :label="true">{{ $t("Refundable") }}</el-radio>
            <el-radio :label="false">{{ $t("Non-refundable") }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('Delivery_Services')" prop="distributionFee">
          <el-radio-group v-model="goods.isDistribution">
            <el-radio :label="false">{{ $t("Delivery_Free") }}</el-radio>
            <el-radio :label="true">{{ $t("Delivery_Fee") }}</el-radio>
          </el-radio-group>
          <el-input
            v-show="goods.isDistribution"
            v-model="goods.distributionFee"
            placeholder="配送费"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>

<!--    <el-card class="box-card">
      <h4>{{ $t("Merchandise_Parameters") }}</h4>
      <el-button
        icon="el-icon-circle-plus"
        :plain1="true"
        type="primary"
        @click="handleAttributeShow"
        >{{ $t("Add") }}</el-button
      >
      <el-table :data="attributes">
        <el-table-column
          property="attribute"
          :label="$t('Merchandise_parameter_names')"
        />
        <el-table-column
          property="value"
          :label="$t('Merchandise_parameter_values')"
        />
        <el-table-column
          align="center"
          :label="$t('Operate')"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot="header" slot-scope="{ row }">
            {{ $t("Operate") }}
            <i class="el-icon-s-tools" style="color: #d35e32"></i>
          </template>
          <template slot-scope="scope">
            <el-button
              icon="el-icon-delete"
              plain1
              round
              type="danger"
              size="mini"
              @click="handleAttributeDelete(scope.row)"
              >{{ $t("Delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        :visible.sync="attributeVisiable"
        :title="$t('Set_merchandise_parameter_values')"
      >
        <el-form
          ref="attributeForm"
          :model="attributeForm"
          status-icon
          label-position="left"
          label-width="250px"
          style="width: 500px; margin-left: 50px"
        >
          <el-form-item
            :label="$t('Merchandise_parameter_names')"
            prop="attribute"
          >
            <el-input v-model="attributeForm.attribute" />
          </el-form-item>
          <el-form-item
            :label="$t('Merchandise_parameter_values')"
            prop="value"
          >
            <el-input v-model="attributeForm.value" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            icon="el-icon-error"
            plain1
            @click="attributeVisiable = false"
            >{{ $t("Cancel") }}</el-button
          >
          <el-button
            icon="el-icon-success"
            plain1
            type="primary"
            @click="handleAttributeAdd"
            >{{ $t("Confirm") }}</el-button
          >
        </div>
      </el-dialog>
    </el-card>-->

    <div class="op-container">
      <el-button icon="el-icon-error" plain1 @click="handleCancel">{{
        $t("Cancel")
      }}</el-button>
      <el-button
        icon="el-icon-s-promotion"
        plain1
        type="primary"
        @click="handleEdit"
        >{{ $t("Renew_Merchandise") }}</el-button
      >
    </div>
  </div>
</template>

<script>
import {
  detailGoods,
  editGoods,
  listCatAndBrand,
  goodsAddSpec,
  goodsUpdateSpec,
  goodsDeleteSpec,
  goodsAddSpecMer,
  goodsUpdateSpecMer,
  goodsDeleteSpecMer,
  goodsSpecMerList,
  goodsAccessoryMerList,
  goodsAddAccessory,
  goodsUpdateAccessory,
  goodsDeleteAccessory,
  goodsAddProp,
  goodsUpdateProp,
  goodsDeleteProp,
} from "@/api/goods";
import { listCountryRegion, listSubRegion } from "@/api/region";
import { createStorage, uploadPath } from "@/api/storage";
import Editor from "@tinymce/tinymce-vue";
import { MessageBox, Tree } from "element-ui";
import { getToken } from "@/utils/auth";
import { allForPerm } from "@/api/shop";
import { allMerchandise } from "@/api/merchandise";
import { findByRegionId } from "@/api/tax";
import store from "@/store";

//配方
import {
  listFormula,listAllFormula,
  addGoodsFormulaCorrelation,
  unbundleGoodsFormulaCorrelation,
  listGoodsFormulaSpecifications,
  getGoodsFormulaCorrelationDetails,
} from "@/api/formula";
//配方类型
import { listType } from "@/api/formulaType";

import { listFormulaSpecificationsDataProportioning } from "@/api/formulaSpecificationsDataProportioning";
import {
  addFormulaSpecifications,
  updateFormulaSpecifications,
  deleteFormulaSpecifications,
} from "@/api/formulaSpecifications";

//客户定制
import {
  listReplaceableMaterial,
  isCustomization,
  updateIsCustomization,
  addReplaceableMaterial,
  updateReplaceableMaterial,
  deleteReplaceableMaterial,
} from "@/api/replaceableMaterial";
import {updateFormulaMaterial} from "../../api/formulaMaterial";
import { list } from "@/api/materialClassification";
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  name: "GoodsDetail",
  components: { Editor , Pagination },
  data() {
    const validateDouble = (rule, value, callback) => {
      if (!value || !/^[0-9,.]*$/.test(value)) {
        callback(new Error("必须为数字"));
      } else {
        callback();
      }
    };

    const validateRegion = (rule, value, callback) => {
      // 如果是店铺登录则退出不校验
      if (this.shop) {
        callback();
        return;
      }

      if (this.regions.length == 0) {
        callback(new Error("请选择完整的区域信息"));
      }

      let selectedCityIds = [];
      for (let i = 0; i < this.regions.length; i++) {
        let region = this.regions[i];
        let cityId = region.cityId;
        if (!cityId) {
          callback(new Error("请选择完整的区域信息"));
          return;
        } else {
          for (let j = 0; j < selectedCityIds; j++) {
            if (cityId == selectedCityIds[j]) {
              callback(new Error("请勿选择重复的区域信息"));
              return;
            }
          }
          selectedCityIds.push(cityId);
        }
      }

      callback();
    };

    const validatePropertyFormValues = (rule, value, callback) => {
      if (!this.propertyForm.values || this.propertyForm.values.length === 0) {
        callback(new Error("属性不能为空"));
      }

      for (var i = 0; i < this.propertyForm.values.length; i++) {
        if (!this.propertyForm.values[i]) {
          callback(new Error("属性不能为空"));
        }
      }

      callback();
    };

    return {
      //消耗系数
      consumeSystemOptions:[
        {
          value: 0.1,
          label: 0.1,
        },
        {
          value: 0.2,
          label: 0.2,
        },
        {
          value: 0.3,
          label: 0.3,
        },
        {
          value: 0.4,
          label: 0.4,
        },
        {
          value: 0.5,
          label: 0.5,
        },
        {
          value: 0.6,
          label: 0.6,
        },
        {
          value: 0.7,
          label: 0.7,
        },
        {
          value: 0.8,
          label: 0.8,
        },
        {
          value: 0.9,
          label: 0.9,
        },
        {
          value: 1.0,
          label: 1.0,
        },
      ],
      //可替换原料唯一
      materialName: undefined,
      //显示商品规格or配方规格
      showGoodsFormulaTable: true,
      //计费条件数学等式
      options: [
        {
          value: "<",
          label: "小于",
        },
        {
          value: ">",
          label: "大于",
        },
        {
          value: "<=",
          label: "小于等于",
        },
        {
          value: "==",
          label: "等于",
        },
        {
          value: ">=",
          label: "大于等于",
        },
        {
          value: "介于两个数之间",
          label: "介于两个数之间",
        },
        {
          value: "介于两个数之外",
          label: "介于两个数之外",
        },
      ],
      //是否定制
      // isCustomization: undefined,
      //客户定制加载
      customizationFormulaSpecificationsMaterialLoading: false,
      //客户定制集合
      customizationFormulaSpecificationsMaterialList: [],
      //切换
      activeName: "first",
      materialList: [],
      //可替换原料表单
      replaceableMaterialForm: {
        //定制配方
        lumiereCustomizationFormula: {
          goodsId: undefined,
          specificationsId: undefined,
          materialId: undefined,
        },
        //可替换原料
        lumiereReplaceableMaterial: {
          materialClassificationId: undefined,
          materialName: undefined,
          materialImg: undefined,
          surcharge: undefined,
          specificationsDose: undefined,
          quantity: undefined,
          chargingCondition: undefined,
          //chargingConditionNumber: undefined,
          quantityRestrict: undefined,
          unit: undefined,
          consumeSystem: undefined,
          chargingMode: undefined,
        },
      },
      //规格的表单
      formulaSpecificationsForm: {
        id: undefined,
        formulaId: undefined,
        specificationsName: undefined,
        specificationsValue: undefined,
        specificationsImg: undefined,
        specificationsPrice: undefined,
        isDefault: undefined,
        formulaMaterialIds: undefined,
      },
      //弹框显示
      //添加配方规格
      dialogVisible1: false,
      //编辑配方规格
      dialogVisible2: false,
      //编辑配方规格原料数据配比
      dialogVisible3: false,
      //可替换原料弹框
      dialogVisible4: false,
      //编辑可替换原料弹框
      dialogVisible5: false,
      //是否默认
      isCustomizationChecked: undefined,
      //单独的配方
      formulaForm: {},
      //配方类型列表
      formulaTypeList: [],
      //商品配方名称
      goodsFormulaName:'',
      //商品配方规格列表
      goodsFormulaSpecificationsList: [],
      //商品配方规格刷新
      goodsFormulaSpecificationsLoading: false,
      //配方页面刷新
      formulaListLoading: false,
      //配方页面集合
      formulaList: [],
      formulaQueryParam: {
        page: 1,
        limit: 20,
        total: 0,
        status:1,
        formulaName:undefined,
      },
      //配方规格数据配比集合
      formulaSpecificationsDataProportioningList: [],
      //配方规格数据配比刷新
      formulaSpecificationsDataProportioningLoading: false,
      //需要挑战传入的商品配方详情
      formulaDetails: {},

      // 当前店铺
      shop: store.state.user.shop,
      shopRegions: store.state.user.shopRegions,
      shops: [],
      uploadPath,
      hideUpload: false,

      vipPriceForm: {},
      stepPriceForms: [{}],
      moneyOfPriceForms: [{}],
      newKeywordVisible: false,
      newKeyword: "",
      keywords: [],
      galleryFileList: [],
      categoryList: [],
      regionList: [],
      brandList: [],
      categoryIds: [],
      goods: { priceType: "1", gallery: [] },
      regions: [],
      specVisiable: false,
      formulaVisiable: false,
      formulaSpecificationsDataProportioningVisiable: false,
      specForm: { specification: "", value: "", picUrl: "", sort: 0 },
      specEditVisiable: false,
      specEditForm: {
        id: undefined,
        goodsId: undefined,
        specification: undefined,
        value: undefined,
        price: undefined,
        picUrl: undefined,
        sort: undefined,
      },
      specRules: {
        specification: [{ required: true,message: this.$t("请输入规格名"), trigger: "blur" }],
        value: [{ required: true,message: this.$t("请输入规格值"), trigger: "blur" }],
        price: [{ required: true,message: this.$t("请输入价格"), trigger: "blur" }],
        picUrl: [{ required: true,message: this.$t("请输入规格图片"), trigger: "blur" }],
        sort: [{ required: true,message: this.$t("请输入序号"), trigger: "blur" }],
      },
      specMerVisiable: false,
      specMerList: [],
      specMerForm: {
        id: undefined,
        goodsId: undefined,
        goodsSpecificationId: undefined,
        merchandiseId: undefined,
        merchandiseSn: undefined,
        merchandiseName: undefined,
        standard: undefined,
        model: undefined,
        basicUnit: undefined,
        number: undefined,
        consumeRatio: undefined,
      },
      specMerRules: {
        merchandiseId: [{ required: true,message: this.$t("请选择原料"), trigger: "blur" }],
        number: [{ required: true,message: this.$t("请输入数量"), trigger: "blur" }],
        model: [{ required: true,message: this.$t("请输入规格"), trigger: "blur" }],
        consumeRatio: [{ required: true,message: this.$t("请输入消耗系数"), trigger: "blur" }],
      },
      specifications: [
        { specification: "规格", price: 0.0, value: "标准", picUrl: "" },
      ],
      productVisiable: false,
      productForm: {
        id: 0,
        specifications: [],
        price: 0.0,
        number: 0,
        url: "",
        tax: 0.0,
      },
      products: [
        { id: 0, specifications: ["标准"], price: 0.0, number: 0, url: "" },
      ],
      attributeVisiable: false,
      attributeForm: { attribute: "", value: "" },
      attributes: [],
      rules: {
        goodsSn: [
          {
            required: true,
            message: this.$t("Merchandise_ID_must_not_be_empty"),
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("Merchandise_name_must_not_be_empty"),
            trigger: "blur",
          },
        ],
        regionId: [{ trigger: "change", validator: validateRegion }],
      },
      productRules: {
        number: [
          {
            required: true,
            message: this.$t("Stock_amount_cannot_be_empty"),
            trigger: "blur",
          },
          {
            type: "number",
            message: this.$t("Stock_amount_must_be_a_number"),
            trigger: "blur",
          },
        ],
        sellPrice: [
          {
            required: true,
            message: this.$t("Sale_price_cannot_be_empty"),
            trigger: "change",
          },
          { validator: validateDouble, trigger: "change" },
        ],
        costPrice: [
          {
            required: true,
            message: this.$t("Buy-in_cost_cannot_be_empty"),
            trigger: "change",
          },
          { validator: validateDouble, trigger: "change" },
        ],
        /*          tax: [{ required: true, message: '税率不能为空', trigger: 'change' },
                    { validator: validateDouble, trigger: 'change' }],*/
      },
      editorInit: {
        language: "zh_CN",
        convert_urls: false,
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount",
        ],
        toolbar: [
          "searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",
          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen",
        ],
        images_upload_handler: function (blobInfo, success, failure) {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          createStorage(formData)
            .then((res) => {
              success(res.data.data.url);
            })
            .catch(() => {
              failure(this.$t("Upload_failed_please_reupload"));
            });
        },
      },
      taxes: [
        {
          value: 0,
          type: 1,
          enable: false,
        },
        {
          value: 0,
          type: 2,
          enable: false,
        },
        {
          value: 0,
          type: 3,
          enable: false,
        },
      ],
      taxTypeData: [
        {
          value: "GST",
          label: "GST",
        },
        {
          value: "PST",
          label: "PST",
        },
      ],
      costTypeData: [
        {
          value: 0,
          label: this.$t("按次计费"),
        },
        {
          value: 1,
          label: this.$t("按份计费"),
        },
      ],
      // 店铺税类型
      shopTaxTypes: [],
      accessoryVisiable: false,
      accessoryForm: {},
      accessories: [],
      accessoryRules: {
        groupName: [
          {
            required: true,
            message: this.$t("辅料名不能为空"),
            trigger: "blur",
          },
        ],
        merchandiseId: [
          {
            required: true,
            message: this.$t("原料不能为空"),
            trigger: "change",
          },
        ],
        price: [
          {
            required: true,
            message: this.$t("辅料价格不能为空"),
            trigger: "blur",
          },
        ],
        number: [
          {
            required: true,
            message: this.$t("辅料数量不能为空"),
            trigger: "blur",
          },
        ],
        costType: [
          {
            required: true,
            message: this.$t("计费类型不能为空"),
            trigger: "blur",
          },
        ],
        consumeRatio: [
          {
            required: true,
            message: this.$t("消耗系数不能为空"),
            trigger: "blur",
          },
        ],
        fewContent: [
          { required: true, message: this.$t("少量不能为空"), trigger: "blur" },
        ],
        muchContent: [
          { required: true, message: this.$t("多加不能为空"), trigger: "blur" },
        ],
        accessoryGroupName: [
          {
            required: true,
            message: this.$t("选项可填[咖啡因｜糖浆｜牛奶｜或其它]"),
            trigger: "blur",
          },
        ],
      },
      merchandise: [],
      propertyVisiable: false,
      propertyForm: {},
      properties: [],
      propertyRules: {
        name: [
          {
            required: true,
            message: this.$t("属性名不能为空"),
            trigger: "blur",
          },
        ],
        sort: [{ required: true }],
        values: [{ validator: validatePropertyFormValues, trigger: "blur" }],
      },
    };
  },
  computed: {
    headers() {
      return {
        "X-Litemall-Admin-Token": getToken(),
      };
    },
  },
  async created() {
    await this.init();
    this.LoadGoodsFormulaSpecificationsInit();
    this.getGoodsFormulaDetails();
    this.whetherCustomization();
    // 获取并填充原料分类列表
    this.getMaterialClassificationList();
  },
  mounted() {
      this.$nextTick(() => {
          if(this.$route.query.jumpAnchor){
              const target = this.$refs.goodsSpecificationsTitle;
              if (target) {
                  target.scrollIntoView({
                      behavior:'smooth',
                      block:'start'
                  });
              }
          }
      });
  },
  methods: {
    test(val) {
      if (val.length == 3) {
        this.goods.categoryId = val[2];
      }
    },
    init() {
      if (this.$route.query.id == null) {
        return;
      }

      listCatAndBrand().then((response) => {
        this.categoryList = response.data.data.categoryList;
        this.brandList = response.data.data.brandList;
      });

      allForPerm().then((response) => {
        this.shops = response.data.data.list;
      });

      const goodsId = this.$route.query.id;
      detailGoods(goodsId).then((response) => {
        this.goods = response.data.data.goods;
        this.regions = response.data.data.regions;
        this.specifications = response.data.data.specifications;
        this.products = response.data.data.products;
        this.attributes = response.data.data.attributes;
        this.categoryIds = response.data.data.categoryIds;

        this.stepPriceForms =
          response.data.data.ladderPrices.length > 0
            ? response.data.data.ladderPrices
            : [{}];
        this.moneyOfPriceForms =
          response.data.data.maxMinusPrices.length > 0
            ? response.data.data.maxMinusPrices
            : [{}];
        this.vipPriceForm = response.data.data.vipGoodsPrice || {};
        this.accessories = response.data.data.accessories || [];
        this.properties = response.data.data.properties || [];

        // 初始化区域列表
        this.initRegionList();

        // this.taxes = response.data.data.goodsTaxes

        this.galleryFileList = [];
        for (var i = 0; i < this.goods.gallery.length; i++) {
          this.galleryFileList.push({
            url: this.goods.gallery[i],
          });
        }
        if (!this.goods.priceType) {
          this.goods.priceType = "1";
        } else {
          this.goods.priceType = this.goods.priceType + "";
        }
        const keywords = response.data.data.goods.keywords;
        if (keywords !== null) {
          this.keywords = keywords.split(",");
        }
      });

      // //debugger

      // 初始化店铺税务类型
      if (this.shopRegions && this.shopRegions.length == 3) {
        let countryId = this.shopRegions[0].id;
        let provinceId = this.shopRegions[1].id;
        let cityId = this.shopRegions[2].id;
        return findByRegionId(countryId, provinceId, cityId).then(
          (response) => {
            this.shopTaxTypes = response.data.data.list;
          }
        );
      }
    },
    initRegionList() {
      this.regions.forEach((e) => {
        // //debugger
        let region = {
          countrys: [],
          provinces: [],
          citys: [],
          taxTypes: [],
        };
        // 构建国家级别
        listCountryRegion().then((response) => {
          region.countrys = response.data.data.list;
        });

        // 构建省
        let query = {
          id: e.countryId,
          type: 2,
        };
        listSubRegion(query).then((response) => {
          region.provinces = response.data.data.list;
        });

        // 构建城市
        query.id = e.provinceId;
        listSubRegion(query).then((response) => {
          region.citys = response.data.data.list;
        });

        // 加载区域水
        // let cityId = e.cityId
        findByRegionId(e.countryId, e.provinceId, e.cityId).then((response) => {
          region.taxTypes = response.data.data.list;
        });

        this.regionList.push(region);
      });
    },
    addRegion() {
      if(this.regionList.length==0){
        let region = {
          countrys: [],
          provinces: [],
          citys: [],
          taxTypes: []
        }

        listCountryRegion().then(response=>{
          region.countrys = response.data.data.list
        })

        this.regionList.push(region)

        let regionData = {
          countryId: undefined,
          provinceId: undefined,
          cityId: undefined,
          taxTypes: []
        }

        this.regions.push(regionData)
      }

      //复制上一份的数据
      else{
        if(this.regions[0].countryId==undefined){
          this.$notify({
            title: "提示",
            message: "请完善第一条数据",
            type: "warning",
          });
          return;
        }
        this.regionList.push(Object.assign({}, this.regionList[this.regionList.length-1]))
        this.regions.push(Object.assign({}, this.regions[this.regions.length-1]))
      }

    },
    deleteRegion(index) {
      this.regionList.splice(index, 1);
      this.regions.splice(index, 1);
    },
    changeCountry(index, value) {
      this.regionList[index].provinces = [];
      this.regionList[index].citys = [];
      this.regionList[index].taxTypes = [];
      this.regions[index].provinceId = undefined;
      this.regions[index].cityId = undefined;

      let query = {
        id: value,
        type: 2,
      };
      listSubRegion(query).then((response) => {
        this.regionList[index].provinces = response.data.data.list;
      });
    },
    changeProvince(index, value) {
      this.regionList[index].citys = [];
      this.regionList[index].taxTypes = [];
      this.regions[index].cityId = undefined;

      let query = {
        id: value,
        type: 2,
      };
      listSubRegion(query).then((response) => {
        this.regionList[index].citys = response.data.data.list;
      });
    },
    changeCity(index, region, value) {
      let countryId = region.countryId;
      let provinceId = region.provinceId;
      let cityId = region.cityId;
      findByRegionId(countryId, provinceId, cityId).then((response) => {
        this.regionList[index].taxTypes = response.data.data.list;
      });
    },
    handleCategoryChange(value) {
      // this.goods.categoryId = value[value.length - 1]
    },
    handleCancel: function () {
      if (this.shop) {
        this.$router.push({ path: "/goods/shop_list" });
      } else {
        this.$router.push({ path: "/goods/list" });
      }
    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1);
      this.goods.keywords = this.keywords.toString();
    },
    showInput() {
      this.newKeywordVisible = true;
      this.$nextTick((_) => {
        this.$refs.newKeywordInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      const newKeyword = this.newKeyword;
      if (newKeyword) {
        this.keywords.push(newKeyword);
        this.goods.keywords = this.keywords.toString();
      }
      this.newKeywordVisible = false;
      this.newKeyword = "";
    },
    uploadPicUrl: function (response) {
      this.goods.picUrl = response.data.url;
    },
    uploadOverrun: function () {
      this.$message({
        type: "error",
        message: this.$t("上传文件个数不能超出限制！最多上传10张图片!"),
      });
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.goods.gallery.push(response.data.url);
        this.hideUpload = fileList.length >= 10;

      }

    },
    specChanged: function (label) {
      if (label === false) {
        this.specifications = [
          { specification: "规格", value: "标准", picUrl: "" },
        ];
        this.products = [
          { id: 0, specifications: ["标准"], price: 0.0, number: 0, url: "" },
        ];
      } else {
        this.specifications = [];
        this.products = [];
      }
    },
    uploadSpecPicUrl: function (response) {
      this.specForm.picUrl = response.data.url;
    },
    uploadSpecEditPicUrl: function (response) {
      this.specEditForm.picUrl = response.data.url;
    },
    handleSpecificationShow() {
      this.specForm = { specification: "", value: "", picUrl: "" };
      this.specVisiable = true;
    },
    //解除配方绑定
    handleFormulaUnbundle(){
        var goodsFormulaCorrelation = {
            goodsId: this.goods.id,
            formulaId: this.formulaForm.id,
        };
        unbundleGoodsFormulaCorrelation(goodsFormulaCorrelation)
            .then((res) => {
                this.$notify({
                    title: "成功",
                    message: "解除成功",
                    type: "success",
                });
                this.LoadGoodsFormulaSpecifications();
                this.init();
                this.whetherCustomization();
                this.showGoodsFormulaTable = false;
                this.goodsFormulaName = undefined;
            })
            .catch((error) => {
                this.$notify.error({
                    title: "错误",
                    message: "解除失败",
                });
            });
    },
    //选择配方页面打开
    handleFormulaShow() {
      this.handleSearchFormulaList();
      this.formulaVisiable = true;
    },
    //配方规格详情页面打开
    handleFormulaSpecificationsDataProportioningShow(row) {
      this.getFormulaSpecificationsDataProportioning(row.id);
      this.formulaSpecificationsDataProportioningVisiable = true;
    },
    handleSpecificationAdd() {
      this.$refs["specForm"].validate((valid) => {
        if (valid) {
          const sepcData = {
            goodsId: this.goods.id,
            specification: this.specForm.specification,
            value: this.specForm.value,
            price: this.specForm.price,
            picUrl: this.specForm.picUrl,
            sort: this.specForm.sort,
          };

          goodsAddSpec(sepcData)
            .then((response) => {
              const responseData = response.data.data;

              this.$notify.success({
                title: this.$t("Success!"),
                message: "添加成功",
              });

              responseData.merchandises = [];
              this.specifications.push(responseData);

              // 重新排序
              this.specifications.sort(function (a, b) {
                return a.sort - b.sort;
              });

              this.specVisiable = false;
              this.showGoodsFormulaTable = true;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleSpecificationEdit(row) {
      this.specEditForm = {
        id: row.id,
        goodsId: row.goodsId,
        specification: row.specification,
        value: row.value,
        price: row.price,
        picUrl: row.picUrl,
        sort: row.sort,
      };

      this.specEditVisiable = true;
    },
    handleSpecificationEditSubmit() {
      this.$refs["specEditForm"].validate((valid) => {
        if (valid) {
          goodsUpdateSpec(this.specEditForm)
            .then((response) => {
              const responseData = response.data.data;
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 更新本地数据
              this.specifications.forEach((e) => {
                if (e.id == this.specEditForm.id) {
                  e.specification = responseData.specification;
                  e.value = responseData.value;
                  e.price = responseData.price;
                  e.picUrl = responseData.picUrl;
                  e.sort = responseData.sort;
                  e.updateTime = responseData.updateTime;
                }
              });

              // 重新排序
              this.specifications.sort(function (a, b) {
                return a.sort - b.sort;
              });

              this.specEditVisiable = false;
              this.specEditForm = {};
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleSpecificationDelete(row) {
      const specId = row.id;
      goodsDeleteSpec(specId)
        .then((response) => {
          this.$notify.success({
            title: this.$t("Success!"),
            message: "删除成功",
          });

          const index = this.specifications.indexOf(row);
          this.specifications.splice(index, 1);
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    loadGoodsSpecMerList(specId, merchandiseId) {
      goodsSpecMerList(specId, merchandiseId)
        .then((response) => {
          this.specMerList = response.data.data;
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    handleAddSpecMer(row) {
      this.specMerForm = {};

      const specId = row.id;
      this.specMerForm.goodsId = row.goodsId;
      this.specMerForm.goodsSpecificationId = specId;
      this.specMerForm.consumeRatio = 1;

      this.loadGoodsSpecMerList(specId, "");
      this.specMerVisiable = true;
    },
    handleEditSpecMer(row) {
      this.specMerForm = JSON.parse(JSON.stringify(row)); // 拷贝对象，防止同步修改
      this.loadGoodsSpecMerList(row.goodsSpecificationId, row.merchandiseId);
      this.specMerVisiable = true;
    },
    handleAddSpecMerSubmit() {
      this.$refs["specMerForm"].validate((valid) => {
        if (valid) {
          goodsAddSpecMer(this.specMerForm)
            .then((response) => {
              const responseData = response.data.data;
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 添加本地数据
              this.specifications.forEach((e) => {
                if (e.id == this.specMerForm.goodsSpecificationId) {
                  if (!e.merchandises) {
                    e.merchandises = [];
                  }
                  e.merchandises.push(responseData);
                }
              });

              this.specMerVisiable = false;
              this.specMerForm = {};
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleEditSpecMerSubmit() {
      this.$refs["specMerForm"].validate((valid) => {
        if (valid) {
          goodsUpdateSpecMer(this.specMerForm)
            .then((response) => {
              const responseData = response.data.data;
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 添加本地数据
              this.specifications.forEach((e) => {
                if (e.id == this.specMerForm.goodsSpecificationId) {
                  e.merchandises.forEach((mer) => {
                    if (mer.id == responseData.id) {
                      mer.merchandiseId = responseData.merchandiseId;
                      mer.merchandiseName = responseData.merchandiseName;
                      mer.merchandiseSn = responseData.merchandiseSn;
                      mer.standard = responseData.standard;
                      mer.model = responseData.model;
                      mer.basicUnit = responseData.basicUnit;
                      mer.consumeRatio = responseData.consumeRatio;
                      mer.number = responseData.number;
                    }
                  });
                }
              });

              this.specMerVisiable = false;
              this.specMerForm = {};
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleSpecMerSubmit() {
      const id = this.specMerForm.id;
      if (id) {
        this.handleEditSpecMerSubmit();
      } else {
        this.handleAddSpecMerSubmit();
      }
    },
    handleDeleteSpecMer(row) {
      const id = row.id;
      goodsDeleteSpecMer(id)
        .then((response) => {
          this.$notify.success({
            title: this.$t("Success!"),
            message: "操作成功",
          });

          // 删除本地数据
          this.specifications.forEach((e) => {
            const index = e.merchandises.indexOf(row);
            if (index >= 0) {
              e.merchandises.splice(index, 1);
            }
          });
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    changeSpecMerFormMerchandise(value) {
      this.specMerList.forEach((e) => {
        if (e.id === value) {
          this.specMerForm.unit = e.unit;
          this.specMerForm.merchandiseSn = e.merchandiseSn;
          this.specMerForm.merchandiseName = e.name;
          this.specMerForm.standard = e.standard;
          this.specMerForm.model = e.model;
          this.specMerForm.basicUnit = e.basicUnit;
        }
      });
    },
    specToProduct() {
      if (this.specifications.length === 0) {
        return;
      }
      // 根据specifications创建临时规格列表
      var specValues = [];
      var spec = this.specifications[0].specification;
      var values = [];
      values.push(0);

      for (var i = 1; i < this.specifications.length; i++) {
        const aspec = this.specifications[i].specification;

        if (aspec === spec) {
          values.push(i);
        } else {
          specValues.push(values);
          spec = aspec;
          values = [];
          values.push(i);
        }
      }
      specValues.push(values);

      // 根据临时规格列表生产货品规格
      // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
      var productsIndex = 0;
      var products = [];
      var combination = [];
      var n = specValues.length;
      for (var s = 0; s < n; s++) {
        combination[s] = 0;
      }
      var index = 0;
      var isContinue = false;
      do {
        var specifications = [];
        for (var x = 0; x < n; x++) {
          var z = specValues[x][combination[x]];
          specifications.push(this.specifications[z].value);
        }
        products[productsIndex] = {
          id: productsIndex,
          specifications: specifications,
          price: 0.0,
          number: 0,
          url: "",
        };
        productsIndex++;

        index++;
        combination[n - 1] = index;
        for (var j = n - 1; j >= 0; j--) {
          if (combination[j] >= specValues[j].length) {
            combination[j] = 0;
            index = 0;
            if (j - 1 >= 0) {
              combination[j - 1] = combination[j - 1] + 1;
            }
          }
        }
        isContinue = false;
        for (var p = 0; p < n; p++) {
          if (combination[p] !== 0) {
            isContinue = true;
          }
        }
      } while (isContinue);

      this.products = products;
    },
    handleProductShow(row) {
      this.productForm = Object.assign({}, row);
      this.productVisiable = true;
    },
    uploadProductUrl: function (response) {
      this.productForm.url = response.data.url;
    },
    handleProductEdit() {
      for (var i = 0; i < this.products.length; i++) {
        const v = this.products[i];
        if (v.id === this.productForm.id) {
          this.products.splice(i, 1, this.productForm);
          break;
        }
      }
      this.productVisiable = false;
    },
    handleAttributeShow() {
      this.attributeForm = {};
      this.attributeVisiable = true;
    },
    handleAttributeAdd() {
      this.attributes.unshift(this.attributeForm);
      this.attributeVisiable = false;
    },
    handleAttributeDelete(row) {
      const index = this.attributes.indexOf(row);
      this.attributes.splice(index, 1);
    },
    handleStepAdd(row) {
      this.stepPriceForms.push({
        number: undefined,
        price: undefined,
      });
    },
    handleStepDelete(scope) {
      if (this.stepPriceForms.length > 1) {
        this.stepPriceForms.splice(scope.$index, 1);
      } else {
        this.stepPriceForms[0] = {
          number: undefined,
          price: undefined,
        };
      }
    },
    handleMoneyOfAdd(row) {
      this.moneyOfPriceForms.push({
        maxPrice: undefined,
        minusPrice: undefined,
      });
    },
    handleMoneyOfDelete(scope) {
      if (this.moneyOfPriceForms.length > 1) {
        this.moneyOfPriceForms.splice(scope.$index, 1);
      } else {
        this.moneyOfPriceForms[0] = {
          maxPrice: undefined,
          minusPrice: undefined,
        };
      }
    },
    handleRemove: function (file, fileList) {
      for (var i = 0; i < this.goods.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url;
        if (file.response === undefined) {
          url = file.url;
        } else {
          url = file.response.data.url;
        }

        if (this.goods.gallery[i] === url) {
          this.goods.gallery.splice(i, 1);
        }
        this.hideUpload = fileList.length >= 5;

      }
    },
    handleTabSwitch: function (tab) {
      if (tab.name == 1) {
        this.goods.priceType = "1";
        this.moneyOfPriceForms = [{}];
        this.stepPriceForms = [{}];
      } else if (tab.name == 2) {
        this.goods.priceType = "2";
        this.vipPriceForm = {};
        this.moneyOfPriceForms = [{}];
      } else {
        this.goods.priceType = "3";
        this.vipPriceForm = {};
        this.stepPriceForms = [{}];
      }
    },
    handleEdit: function () {
      const finalGoods = {
        goods: this.goods,
        regions: this.regions,
        specifications: this.specifications,
        // products: [this.productForm],
        attributes: this.attributes,
        accessories: this.accessories,
        // goodsTaxes: this.taxes
      };
      this.productForm.taxTypes = [];
      this.taxes.forEach((tax) => {
        if (tax.enable && this.productForm.taxTypes.indexOf(tax) < 0) {
          this.productForm.taxTypes.push(tax.type);
        }
      });
      if (this.goods.priceType == "1") {
        finalGoods.vipPrice = this.vipPriceForm;
      } else if (this.goods.priceType == "2") {
        finalGoods.ladderPrices = this.stepPriceForms;
      } else if (this.goods.priceType == "3") {
        finalGoods.maxMinusPrices = this.moneyOfPriceForms;
      }
      if (this.goods.shopId) {
        this.shops.forEach((shop) => {
          if (this.goods.shopId == shop.id) {
            this.goods.shopName = shop.name;
          }
        });
      }

      let regions = finalGoods.regions;
      for (let regionsKey in regions) {
        if (
          regions[regionsKey].countryId == undefined ||
          regions[regionsKey].provinceId == undefined ||
          regions[regionsKey].cityId == undefined
        ) {
          regions.splice(regionsKey);
        }
      }

      this.$refs["goodsForm"].validate((valid) => {
        if (valid) {
          editGoods(finalGoods)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });
              if (this.shop) {
                this.$router.push({ path: "/goods/shop_list" });
              } else {
                this.$router.push({ path: "/goods/list" });
              }
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleSpecRemove: function () {
      this.specForm.picUrl = undefined;
    },
    handleSpecEditRemove() {
      this.specEditForm.picUrl = undefined;
    },
    handleGoodsPicRemove: function () {
      this.goods.picUrl = undefined;
    },
    filterTaxType(type) {
      if (type == 1) {
        return this.$t("国税");
      } else if (type == 2) {
        return this.$t("省税");
      } else if (type == 3) {
        return this.$t("地方税");
      }
    },
    loadAllMerchandise() {
      allMerchandise({ goodsId: this.$route.query.id }).then((response) => {
        this.merchandise = response.data.data;
      });
    },
    handleAccessoryShow() {
      this.loadAllMerchandise();
      this.accessoryForm = {
        accessoryGroupName: "",
        groupName: "",
        name: "",
        price: 0.0,
        consumeRatio: 1,
      };
      this.accessoryVisiable = true;
    },
    handleAccessoryDelete(row) {
      goodsDeleteAccessory(row.id)
        .then((response) => {
          this.$notify.success({
            title: this.$t("Success!"),
            message: "操作成功",
          });
          const index = this.accessories.indexOf(row);
          this.accessories.splice(index, 1);
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    handleAccessoryEdit(row) {
      this.loadAllMerchandise();
      this.accessoryForm = JSON.parse(JSON.stringify(row)); // 拷贝对象，防止同步修改
      this.accessoryVisiable = true;
    },
    handleAccessoryAdd() {
      const id = this.accessoryForm.id;
      if (id) {
        this.handleAccessoryEditSubmit();
      } else {
        this.handleAccessoryAddSubmit();
      }
    },
    handleAccessoryAddSubmit() {
      this.accessoryForm.goodsId = this.goods.id;
      this.$refs["accessoryForm"].validate((valid) => {
        if (valid) {
          goodsAddAccessory(this.accessoryForm)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "添加成功",
              });

              const responseData = response.data.data;
              this.accessories.push(responseData);
              this.accessoryVisiable = false;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },
    handleAccessoryEditSubmit() {
      this.accessoryForm.goodsId = this.goods.id;
      this.$refs["accessoryForm"].validate((valid) => {
        if (valid) {
          goodsUpdateAccessory(this.accessoryForm)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 更新本地信息
              const responseData = response.data.data;
              this.accessories.forEach((e) => {
                if (e.id == responseData.id) {
                  e.groupName = responseData.groupName;
                  e.groupNameEn = responseData.groupNameEn;
                  e.price = responseData.price;
                  e.merchandiseId = responseData.merchandiseId;
                  e.name = responseData.name;
                  e.number = responseData.number;
                  e.consumeRatio = responseData.consumeRatio;
                  e.costType = responseData.costType;
                }
              });

              this.accessoryVisiable = false;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }

        const goodsId = this.$route.query.id;
        detailGoods(goodsId).then((response) => {
          this.accessories = response.data.data.accessories || [];
        });
      });
    },
    handleAccessoryMerChange() {
      let m = this.merchandise.find((item) => {
        if (item.id == this.accessoryForm.merchandiseId) {
          return item;
        }
      });
      this.accessoryForm.groupName = m.name;
      this.accessoryForm.name = m.name;
      this.accessoryForm.model = m.model;
      this.accessoryForm.unit = m.unit;
      this.accessoryForm.basicUnit = m.basicUnit;
    },
    //改版
    handleAccessoryMerChangeNew() {
      let m = this.merchandise.find((item) => {
        if (item.name == this.replaceableMaterialForm.lumiereReplaceableMaterial.materialName) {
          return item;
        }
      });
      this.accessoryForm.groupName = m.name;
      this.accessoryForm.name = m.name;
      this.accessoryForm.model = m.model;
      this.accessoryForm.unit = m.unit;
      this.accessoryForm.basicUnit = m.basicUnit;
    },

    getMaterialClassificationList() {
        var materialClassification = {
            page: 1,
            limit: 10,
            classificationName: undefined,
        };
        list(materialClassification)
            .then((response) => {
                this.materialList = response.data.data;
            })
            .catch(() => {
                this.list = [];
            });
    },

    //获取原料分类层级
    handleCascaderChangeMaterialId(value) {
        // 当用户选择原料名称时，将其存储在 formulaMaterialForm.materialClassificationId 中
        this.replaceableMaterialForm.lumiereReplaceableMaterial.materialClassificationId =
            value[value.length - 1];
    },
    getCostType(costType) {
      let label = "";
      this.costTypeData.forEach((e) => {
        if (e.value == costType) {
          label = e.label;
        }
      });

      return label;
    },
    handlePropertyShow() {
      this.propertyForm = { name: "", sort: 0, values: [] };
      this.propertyVisiable = true;
    },
    handlePropertyValueAdd() {
      this.propertyForm.values.push("");
    },
    handlePropertyValueDelete(index) {
      this.propertyForm.values.splice(index, 1);
    },
    handlePropertyDelete(row) {
      goodsDeleteProp(row.id)
        .then((response) => {
          this.$notify.success({
            title: this.$t("Success!"),
            message: "操作成功",
          });
          const index = this.properties.indexOf(row);
          this.properties.splice(index, 1);
        })
        .catch((response) => {
          MessageBox.alert(
            this.$t("Error") + this.$t(response.data.errmsg),
            this.$t("Warning"),
            {
              confirmButtonText: this.$t("Confirm"),
              type: "error",
            }
          );
        });
    },
    handlePropertyEdit(row) {
      this.propertyForm = row;
      this.propertyVisiable = true;
    },
    handlePropertyAdd() {
      const id = this.propertyForm.id;
      if (id) {
        this.handlePropertyEditSubmit();
      } else {
        this.handlePropertyAddSubmit();
      }
    },
    handlePropertyAddSubmit() {
      this.propertyForm.goodsId = this.goods.id;

      // 检查属性值是否重复
      const values = this.propertyForm.values.map(v => v.trim()).filter(v => v !== "");
      const duplicates = values.filter((item, index) => values.indexOf(item) !== index);
      if (duplicates.length > 0) {
        this.$message.warning(`属性值中存在重复项：${[...new Set(duplicates)].join("，")}，请修改后再提交`);
        return;
      }

      this.$refs["propertyForm"].validate((valid) => {
        if (valid) {
          goodsAddProp(this.propertyForm)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "添加成功",
              });

              const responseData = response.data.data;
              this.properties.push(responseData);

              // 重新排序
              this.properties.sort(function (a, b) {
                return a.sort - b.sort;
              });

              this.propertyVisiable = false;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },

    handlePropertyEditSubmit() {
      this.propertyForm.goodsId = this.goods.id;

      // 检查是否有重复的属性值
      const values = this.propertyForm.values.map(v => v.trim()).filter(v => v !== "");
      const duplicates = values.filter((item, index) => values.indexOf(item) !== index);
      if (duplicates.length > 0) {
        this.$message.warning(`属性值中存在重复项：${[...new Set(duplicates)].join("，")}，请修改后再提交`);
        return;
      }

      this.$refs["propertyForm"].validate((valid) => {
        if (valid) {
          goodsUpdateProp(this.propertyForm)
            .then((response) => {
              this.$notify.success({
                title: this.$t("Success!"),
                message: "修改成功",
              });

              // 更新本地信息
              const responseData = response.data.data;
              this.properties.forEach((e) => {
                if (e.id == responseData.id) {
                  e.name = responseData.name;
                  e.sort = responseData.sort;
                  e.values = responseData.values;
                }
              });

              // 重新排序
              this.properties.sort((a, b) => a.sort - b.sort);
              this.propertyVisiable = false;
            })
            .catch((response) => {
              MessageBox.alert(
                this.$t("Error") + this.$t(response.data.errmsg),
                this.$t("Warning"),
                {
                  confirmButtonText: this.$t("Confirm"),
                  type: "error",
                }
              );
            });
        }
      });
    },

    handleSearchFormulaList(){
      this.formulaQueryParam.page = 1;
      this.getFormulaList()
    },
    //配方列表查询
    getFormulaList() {
      this.formulaListLoading = true;
      listAllFormula(this.formulaQueryParam)
        .then((response) => {
          this.formulaList = response.data.data.list;
          this.formulaQueryParam.total = response.data.data.total;
          this.formulaListLoading = false;
        })
        .catch(() => {
          this.formulaList = [];
          this.formulaListLoading = false;
        });
      //选择配方时获取配方类型
      this.getFormulaTypeList();
    },

    //获取配方类型列表
    getFormulaTypeList() {
      var listFormulaTypeQuery = {
        page: 1,
        limit: 10,
        classificationName: undefined,
        formulaTypeId: undefined,
      };
      listType(listFormulaTypeQuery)
        .then((response) => {
          this.formulaTypeList = response.data.data.list;
        })
        .catch(() => {
          this.formulaTypeList = [];
        });
    },

    //去创建配方
    handleCreatePath(){
      this.$router.push({
        path: "/formula/formulaList",
        query: {},
      });
    },
    //去编辑
    handlePath(row){
      let formulaType; // 改为 let 声明
      for (let lengthKey in this.formulaTypeList) {
        if (this.formulaTypeList[lengthKey].id === row.formulaTypeId) {
          formulaType = this.formulaTypeList[lengthKey].type;
          break; // 找到后可以提前退出循环
        }
      }

      this.$router.push({
        path: "/formula/formulaSpecifications",
        query: {
          formulaMaterialList:[],
          formulaId: row.id,
          formulaName: row.formulaName,
          type: formulaType,
        },
      });
    },

    //获取配方类型名称
    formateFormulaType(row) {
      for (let lengthKey in this.formulaTypeList) {
        if (this.formulaTypeList[lengthKey].id == row.formulaTypeId) {
          return this.formulaTypeList[lengthKey].formulaTypeName;
        }
      }
    },

    //获取配方类型颜色
    formateFormulaTypeColour(row) {
      for (let lengthKey in this.formulaTypeList) {
        if (this.formulaTypeList[lengthKey].id == row.formulaTypeId) {
          return this.formulaTypeList[lengthKey].typeColour;
        }
      }
    },
    getIndex(index) {
      return (index + 1) + (this.formulaQueryParam.page - 1) * this.formulaQueryParam.limit;
    },
    //选择配方列表单选触发
    handleCurrentChange(val) {
      this.formulaForm = val;
    },

    //选择配方列表提交
    sumbitGoodsFormula() {
      console.log(this.formulaForm.id);
      console.log(this.goods.id);
      var goodsFormulaCorrelation = {
        goodsId: this.goods.id,
        formulaId: this.formulaForm.id,
      };
      addGoodsFormulaCorrelation(goodsFormulaCorrelation)
        .then((res) => {
          if (res.data.data == 100) {
            this.$notify({
              title: "警告",
              message: "这是一条警告的提示消息",
              type: "warning",
            });
            // this.detailGoods(goodsId).then((response) => {
            //   this.specifications = response.data.data.specifications;
            // });
          } else {
            this.formulaVisiable = false;
            this.$notify({
              title: "成功",
              message: "切换成功",
              type: "success",
            });
          }
          this.LoadGoodsFormulaSpecifications();
          this.init();
          this.whetherCustomization();
          this.showGoodsFormulaTable = false;
        })
        .catch((error) => {
          this.$notify.error({
            title: "错误",
            message: "创建失败",
          });
        });
    },

    //加载商品配方规格数据
    LoadGoodsFormulaSpecifications() {

      this.goodsFormulaSpecificationsLoading = true;
      var listQuery = {
        goodsId: this.$route.query.id,
      };
      listGoodsFormulaSpecifications(listQuery)
        .then((response) => {

          this.goodsFormulaSpecificationsList = response.data.data.goodsFormulaSpecifications;
          if(this.goodsFormulaSpecificationsList != []){
            this.showGoodsFormulaTable = false;
            this.goodsFormulaSpecificationsLoading = false;
          }
        })
        .catch(() => {
          this.goodsFormulaSpecificationsList = [];
          this.goodsFormulaSpecificationsLoading = false;
        });
    },

    //加载商品配方规格数据
    LoadGoodsFormulaSpecificationsInit() {
      this.goodsFormulaSpecificationsLoading = true;
      var listQuery = {
        goodsId: this.$route.query.id,
      };
      listGoodsFormulaSpecifications(listQuery)
        .then((response) => {
          this.goodsFormulaSpecificationsList = response.data.data.goodsFormulaSpecifications;
          this.goodsFormulaName = response.data.data.goodsFormulaName;
          this.activeName = this.goodsFormulaSpecificationsList[0].id + "";
          if(this.goodsFormulaSpecificationsList != []){
             this.handleClick(
                { name: this.goodsFormulaSpecificationsList[0].id },
                null
              );
            this.showGoodsFormulaTable = false;
            this.goodsFormulaSpecificationsLoading = false;
          }
        })
        .catch(() => {
          this.goodsFormulaSpecificationsList = [];
          this.goodsFormulaSpecificationsLoading = false;
        });
    },

    //通过规格id查询配方规格数据配比
    getFormulaSpecificationsDataProportioning(formulaSpecificationsId) {
      this.formulaSpecificationsDataProportioningLoading = true;
      var formulaSpecificationsDataProportioning = {
        formulaSpecificationsId: parseInt(formulaSpecificationsId, 10),
      };
      listFormulaSpecificationsDataProportioning(
        formulaSpecificationsDataProportioning
      )
        .then((response) => {
          this.formulaSpecificationsDataProportioningList =
            response.data.data;
          this.formulaSpecificationsDataProportioningLoading = false;
        })
        .catch(() => {
          this.formulaSpecificationsDataProportioningList = [];
          this.formulaSpecificationsDataProportioningLoading = false;
        });
    },

    //去编辑
    handeleAddSpecifications() {
      console.log(this.formulaDetails);
      this.$router.push({
        path: "/formula/formulaSpecifications",
        // query: { id: row.id, type: 1, showType: row.status == 1 ? 2 : 1 },
        query: {
          formulaMaterialList: this.formulaDetails.children,
          formulaId: this.formulaDetails.id,
          formulaName: this.formulaDetails.formulaName,
          type:this.formulaDetails.type
        },
      });
    },

    getGoodsFormulaDetails() {
      var listQuery = {
        goodsId: this.$route.query.id,
      };
      getGoodsFormulaCorrelationDetails(listQuery)
        .then((response) => {
          this.formulaDetails = response.data.data;
        })
        .catch(() => {
          this.formulaDetails = [];
        });
    },

    //关闭规格弹窗
    handleCloseFormulaSpecifications(done) {
      this.init();
      done();
    },
    //编辑规格弹窗
    handerEditFormulaSpecifications(row) {
      this.dialogVisible2 = true;
      this.formulaSpecificationsForm.id = row.id;
      this.formulaSpecificationsForm.formulaId = row.formulaId;
      this.formulaSpecificationsForm.specificationsName =
        row.specificationsName;
      this.formulaSpecificationsForm.specificationsValue =
        row.specificationsValue;
      this.formulaSpecificationsForm.specificationsImg = row.specificationsImg;
      this.formulaSpecificationsForm.specificationsPrice =
        row.specificationsPrice;
      this.formulaSpecificationsForm.isDefault = row.isDefault;
      this.formulaSpecificationsForm.formulaMaterialIds = undefined;
    },

    //删除规格
    handerDeleteFormulaSpecifications(row) {
      var formulaSpecificationsForm = {
        id: row.id,
      };
      this.$confirm("确认删除？")
        .then((_) => {
          deleteFormulaSpecifications(formulaSpecificationsForm)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });
              this.LoadGoodsFormulaSpecifications();
            })
            .catch((res) => {
              this.$notify.error({
                title: "错误",
                message: "删除失败",
              });
            });
        })
        .catch((_) => {});
    },

    //切换规格
    handleClick(tab, event) {
      console.log(1231232132123213);
      console.log(tab, event);
      console.log(tab.name);
      //debugger
      this.getCustomizationFormulaSpecificationsMaterial(tab.name);
      this.replaceableMaterialForm.lumiereCustomizationFormula.specificationsId =
        parseInt(tab.name, 10);

      // this.formulaDataProportioningForm.formulaSpecificationsId = parseInt(
      //   tab.name,
      //   10
      // );
    },

    //客户定制查询
    getCustomizationFormulaSpecificationsMaterial(formulaSpecificationsId) {
      this.customizationFormulaSpecificationsMaterialLoading = true;
      var customizationFormulaSpecificationsMaterial = {
        goodsId: this.$route.query.id,
        specificationsId: parseInt(formulaSpecificationsId, 10),
      };
      listReplaceableMaterial(customizationFormulaSpecificationsMaterial)
        .then((response) => {
          this.customizationFormulaSpecificationsMaterialList =
            response.data.data.list;
          this.customizationFormulaSpecificationsMaterialLoading = false;
        })
        .catch(() => {
          this.customizationFormulaSpecificationsMaterialList = [];
          this.customizationFormulaSpecificationsMaterialLoading = false;
        });
      console.log(this.customizationFormulaSpecificationsMaterialList)
    },

    //是否定制
    whetherCustomization() {
      var goodsFormulaCorrelation = {
        goodsId: this.$route.query.id,
      };
      isCustomization(goodsFormulaCorrelation)
        .then((response) => {
          this.isCustomizationChecked = response.data.data.isCustomization;
          this.LoadGoodsFormulaSpecificationsInit();
        })
        .catch(() => {
          this.isCustomizationChecked = undefined;
        });
    },

    //修改是否定制
    updateWhetherCustomization() {
      var goodsFormulaCorrelation = {
        goodsId: this.$route.query.id,
        isCustomization: this.isCustomizationChecked ? true : false,
      };
      updateIsCustomization(goodsFormulaCorrelation)
        .then((res) => {
          this.$notify({
            title: "成功",
            message: "操作成功",
            type: "success",
          });
        })
        .catch((res) => {
          this.$notify.error({
            title: "错误",
            message: "操作失败",
          });
        });
    },

    //设置是否有数量
    handleFormulaMaterialIsNum(formulaMaterialReplaceableMaterialDTO){
        updateFormulaMaterial({id:formulaMaterialReplaceableMaterialDTO.id,isNum:formulaMaterialReplaceableMaterialDTO.isNum}).then((res) => {
            this.$notify({
                title: "成功",
                message: "添加成功",
                type: "success",
            });

        })
            .catch((res) => {
                formulaMaterialReplaceableMaterialDTO.isNum = !formulaMaterialReplaceableMaterialDTO.isNum
                this.$notify.error({
                    title: "错误",
                    message: "添加失败",
                });
            });
    },

    //添加可替换原料弹窗
    handerAddReplaceableMaterial(row) {
      console.log(888888888888888888888888888888);
      console.log(row);
      this.dialogVisible4 = true;
      this.replaceableMaterialForm.lumiereCustomizationFormula.goodsId =
        parseInt(this.$route.query.id, 10);
      this.replaceableMaterialForm.lumiereCustomizationFormula.formulaId =
        row.adminFormulaMaterialReplaceableMaterialDTO.formulaId;
      this.replaceableMaterialForm.lumiereCustomizationFormula.materialId =
        row.adminFormulaMaterialReplaceableMaterialDTO.id;

      const result = this.getNumberAndSymbolFromComparisonString(row.chargingCondition)
      this.replaceableMaterialForm.lumiereReplaceableMaterial = {
        materialName: row.adminFormulaMaterialReplaceableMaterialDTO.materialName,
        materialImg: row.adminFormulaMaterialReplaceableMaterialDTO.materialImg,
        surcharge: row.surcharge,
        specificationsDose: row.specificationsDose,
        quantity: row.quantity,
        chargingCondition: row.chargingCondition,
        //chargingConditionNumber: result.number,
        quantityRestrict: row.quantityRestrict,
        chargingMode: row.chargingMode,
        unit: row.unit,
        consumeSystem: row.consumeSystem
      };
      //加载原料
      this.handleAccessoryShow();
      this.accessoryForm.basicUnit = row.unit

      this.materialName = row.adminFormulaMaterialReplaceableMaterialDTO.materialName
    },

    //添加可替换原料
    submitAddReplaceableMaterial(form) {

      if(this.materialName  === form.lumiereReplaceableMaterial.materialName){
        this.$notify.error({
          title: "错误",
          message: "原料已被使用",
        });
        return;
      }

      form.lumiereReplaceableMaterial.chargingCondition = form.lumiereReplaceableMaterial.chargingCondition + form.lumiereReplaceableMaterial.chargingConditionNumber;
      var lumiereReplaceableMaterialVO = JSON.stringify(form);
      console.log(lumiereReplaceableMaterialVO)
      addReplaceableMaterial(form)
        .then((res) => {
          this.$notify({
            title: "成功",
            message: "添加成功",
            type: "success",
          });
          this.dialogVisible4 = false;
          // console.log(form)
          // console.log(88888)
          // console.log(this.customizationFormulaSpecificationsMaterialList)


          form.lumiereReplaceableMaterial.id = res.data.data;
          //添加原料不刷新页面，手动添加
          const materialId = form.lumiereCustomizationFormula.materialId;
          const index = this.customizationFormulaSpecificationsMaterialList.findIndex(item => item.adminFormulaMaterialReplaceableMaterialDTO.id === materialId);

          if (index !== -1) {
            this.customizationFormulaSpecificationsMaterialList[index].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.splice(this.customizationFormulaSpecificationsMaterialList[index].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.length,0,form.lumiereReplaceableMaterial)
            //this.$set(this.customizationFormulaSpecificationsMaterialList[index], 'replaceableMaterialList', this.customizationFormulaSpecificationsMaterialList[index].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.map(re=> Object.assign({},re)));
          }


        })
        .catch((res) => {
          this.$notify.error({
            title: "错误",
            message: "添加失败",
          });
        });
    },

    //编辑可替换原料弹窗
    handerUpdateReplaceableMaterial(row) {
      console.log(99)
      console.log(row);
      this.dialogVisible5 = true;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.id = row.id;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.materialName = row.materialName;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.specificationsDose = row.specificationsDose;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.quantity = row.quantity;
      const result = this.getNumberAndSymbolFromComparisonString(
        row.chargingCondition
      );
      this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingCondition = result.symbol;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingConditionNumber = result.number;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.surcharge = row.surcharge;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.quantityRestrict = row.quantityRestrict;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.unit = row.unit;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingMode = row.chargingMode;
      this.replaceableMaterialForm.lumiereReplaceableMaterial.consumeSystem = row.consumeSystem;
      //加载原料
      this.handleAccessoryShow();

      this.accessoryForm.basicUnit = row.unit
    },

    //提交编辑可替换原料
    submitUpdateReplaceableMaterial(form) {
     /* this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingCondition =
        this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingCondition +
        this.replaceableMaterialForm.lumiereReplaceableMaterial.chargingConditionNumber;*/
      updateReplaceableMaterial(this.replaceableMaterialForm.lumiereReplaceableMaterial)
        .then((res) => {
          this.$notify({
            title: "成功",
            message: "编辑成功",
            type: "success",
          });
          this.dialogVisible5 = false;

          //debugger
          //父位置
          let parentIndex = -1;
          //子位置
          let childIndex = -1;

          parentIndex = this.customizationFormulaSpecificationsMaterialList.findIndex(item => {
              childIndex = item.adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.findIndex(itemChildren => itemChildren.id === res.data.data);
              return childIndex !== -1; // 如果找到子元素，则返回true，终止遍历
          });

          if (childIndex !== -1) {
            this.customizationFormulaSpecificationsMaterialList[parentIndex].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.splice(childIndex,1,form)
          }

        })
        .catch((res) => {
          this.$notify.error({
            title: "错误",
            message: "编辑失败",
          });
        });
    },

    //删除可替换原料
    handerDeleteReplaceableMaterial(row) {
      var replaceableMaterialForm = {
        id: row.id
      };
      this.$confirm("确认删除？")
        .then((_) => {
          deleteReplaceableMaterial(replaceableMaterialForm)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });

              //父位置
              let parentIndex = -1;
              //子位置
              let childIndex = -1;

              parentIndex = this.customizationFormulaSpecificationsMaterialList.findIndex(item => {
                  childIndex = item.adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.findIndex(itemChildren => itemChildren.id === replaceableMaterialForm.id);
                  return childIndex !== -1; // 如果找到子元素，则返回true，终止遍历
              });

              if (childIndex !== -1) {
                this.customizationFormulaSpecificationsMaterialList[parentIndex].adminFormulaMaterialReplaceableMaterialDTO.replaceableMaterialList.splice(childIndex,1)
              }

            })
            .catch((res) => {
              this.$notify.error({
                title: "错误",
                message: "删除失败",
              });
            });
        })
        .catch((_) => {});
    },

    //分割特殊字符和数字
    getNumberAndSymbolFromComparisonString(str) {
      // 检查输入是否为非空字符串
      if (typeof str !== "string" || str.trim() === "") {
        return { number: null, symbol: null };
      }

      // 使用正则表达式分别提取符号和数字
      const symbolMatch = str.match(/[<>=!]+/); // 匹配符号
      const numberMatch = str.match(/-?\d+(\.\d+)?/); // 匹配整数和浮点数，包括负数

      // 提取符号和数字
      const symbol = symbolMatch ? symbolMatch[0] : null;
      const number = numberMatch ? parseFloat(numberMatch[0]) : null;

      return { number, symbol };
    },
  },
};
</script>

<style>
.el-card {
  margin-bottom: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

.avatar-uploader__status_label {
  display: block;
  color: red;
}

.inline,
.inline input {
  display: inline;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0; /* 可以根据需要调整 */
}

.dialog-footer .el-button {
  margin-left: 10px; /* 间隔 */
}

</style>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
